# -*- coding: utf-8 -*-
# created on 2017/01/17

from sympy import Interval, oo, S
from mathsolver.functions.base import BaseFunction, BaseValue
from mathsolver.functions.hanshu.helper import check_inter


def dandiao_opposite(dandiao):
    """返回相反的单调性"""
    if '增' in dandiao:
        return '减'
    elif '减' in dandiao:
        return '增'
    else:
        raise ValueError('未知单调性类型： %s' % dandiao)


def jiou_infer_dandiao(jiou, inter, dandiao):
    """根据函数f(x)奇偶性和在某个区间的单调性，推导f(x)在 R 上单调性"""
    inter_min, inter_max = inter._inf, inter._sup
    if inter_min >= 0:
        expanded_inter = Interval(0, oo)
        symmetric_inter = Interval(-oo, 0)
    elif inter_max <= 0:
        expanded_inter = Interval(-oo, 0)
        symmetric_inter = Interval(0, oo)
    else:
        raise ValueError("区间 %s 包含0，无法处理" % inter)

    if '奇' in jiou:
        dandiaoxing = [[S.Reals, dandiao]]
    elif '偶' in jiou:
        dandiaoxing = [[expanded_inter, dandiao], [symmetric_inter, dandiao_opposite(dandiao)]]
    else:
        raise ValueError("未知奇偶性类型： %s" % jiou)

    step = '根据函数奇偶性性质可知，函数 f(x)'
    step += '，'.join('在区间 %s 上单调%s' % (qujian, dandiao) for qujian, dandiao in dandiaoxing)

    return dandiaoxing, step


class JiOuDanDiao(BaseFunction):
    """函数奇偶性判断单调性"""

    def solver(self, *args):
        jiou, inter, dandiao, q_inter = args
        inter, q_inter = check_inter(inter), check_inter(q_inter)
        dandiaoxing, step = jiou_infer_dandiao(jiou, inter, dandiao)
        for qujian, dandiao in dandiaoxing:
            if q_inter.is_subset(qujian):
                res = dandiao
                break
        self.steps.append(['', step])
        self.steps.append(['', '所以函数在 %s 上为单调%s函数' % (q_inter, res)])

        self.output.append(BaseValue(res))
        self.label.add('函数奇偶性判断单调性')
        return self


if __name__ == '__main__':
    pass
